package blue.http.internal.core.mapping;

import blue.http.core.filter.HttpFilter;
import blue.http.core.message.HttpRequest;
import blue.http.core.message.HttpResponse;
import blue.http.internal.core.handler.HttpHandlerChain;
import blue.http.internal.core.parser.FilterConfigCache;
import blue.http.internal.core.parser.HttpConfigCache;
import blue.http.internal.core.parser.HttpMethodResult;
import blue.http.internal.core.parser.HttpUrlKey;
import blue.http.internal.core.parser.ParserFactory;

import java.util.List;

/**
 * @author Jin Zheng
 * @since 1.0 2020-01-07
 */
public class HttpHandlerMapping implements HandlerMapping<HttpRequest, HttpResponse> {
	private final HttpConfigCache httpConfigCache;
	private final FilterConfigCache filterCache;

	public HttpHandlerMapping(ParserFactory parserFactory) {
		this.httpConfigCache = parserFactory.getHttpConfigCache();
		this.filterCache = parserFactory.getFilterConfigCache();
	}

	@Override
	public boolean accepted(Object request) {
		return request != null && request instanceof HttpRequest;
	}

	@Override
	public HttpHandlerChain getHandlerChain(HttpRequest request) {
		HttpUrlKey key = new HttpUrlKey(request.getUrl(), request.getHttpMethod());
		HttpMethodResult result = httpConfigCache.getConfig(key);
		if (result == null) {
			return null;
		}

		List<HttpFilter> filterList = filterCache.matchHttpFilter(request.getUrl());
		var chain = new HttpHandlerChain(result, filterList);
		return chain;
	}
}
